// eslint-disable-next-line import/no-extraneous-dependencies
import { Request, Response } from 'express';
import { parse } from 'url';
import { LineListItem, LineListParams } from '@/pages/Line/data';
import Mock from 'mockjs';

var Random = Mock.Random;
// mock tableListDataSource
const genList = (current: number, pageSize: number) => {
  const lineListDataSource: LineListItem[] = [];

  for (let i = 0; i < pageSize; i += 1) {
    const index = (current - 1) * 10 + i;
    lineListDataSource.push({
      id: index + '',
      name: `地铁${index}号线`,
      startStation: Random.county(),
      endStation: Random.county(),
      direction: '0',
      totalLength: Math.floor(Math.random() * 100) + '',
      interval: 3,
      minTicket: Random.integer(3, 5) + '',
      maxTicket:  Random.integer(9, 12) + '',
      status: '0'
    });
  }
  lineListDataSource.reverse();
  return lineListDataSource;
};

let lineListDataSource = genList(1, 100);

function getLines(req: Request, res: Response, u: string) {
  let realUrl = u;
  if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
    realUrl = req.url;
  }
  const { current = 1, pageSize = 10 } = req.query;
  const params = (parse(realUrl, true).query as unknown) as LineListParams;

  let dataSource = [...lineListDataSource].slice(
    ((current as number) - 1) * (pageSize as number),
    (current as number) * (pageSize as number),
  );
  const sorter = JSON.parse(params.sorter as any);
  if (sorter) {
    dataSource = dataSource.sort((prev, next) => {
      let sortNumber = 0;
      Object.keys(sorter).forEach((key) => {
        if (sorter[key] === 'descend') {
          if (prev[key] - next[key] > 0) {
            sortNumber += -1;
          } else {
            sortNumber += 1;
          }
          return;
        }
        if (prev[key] - next[key] > 0) {
          sortNumber += 1;
        } else {
          sortNumber += -1;
        }
      });
      return sortNumber;
    });
  }
  if (params.filter) {
    const filter = JSON.parse(params.filter as any) as {
      [key: string]: string[];
    };
    if (Object.keys(filter).length > 0) {
      dataSource = dataSource.filter((item) => {
        return Object.keys(filter).some((key) => {
          if (!filter[key]) {
            return true;
          }
          if (filter[key].includes(`${item[key]}`)) {
            return true;
          }
          return false;
        });
      });
    }
  }
  const result = {
    data: dataSource,
    total: lineListDataSource.length,
    success: true,
    pageSize,
    current: parseInt(`${params.currentPage}`, 10) || 1,
  };

  return res.json(result);
}

function postLine(req: Request, res: Response, u: string, b: Request) {
  let realUrl = u;
  if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
    realUrl = req.url;
  }

  const body = (b && b.body) || req.body;
  const { method, name, desc, id } = body;

  switch (method) {
    /* eslint no-case-declarations:0 */
    case 'delete':
      lineListDataSource = lineListDataSource.filter((item) => id.indexOf(item.id) === -1);
      break;
    case 'post':
      (() => {
        const newLine = {
          id: lineListDataSource.length + '',
          num: `B1${Math.floor(Math.random() * 10) % 2}`,
          capacity: Math.floor(Math.random() * 1000),
          line: '二号线',
          status: '1'
        };
        lineListDataSource.unshift(newLine);
        return res.json(newLine);
      })();
      return;

    case 'update':
      (() => {
        let newLine = {};
        lineListDataSource = lineListDataSource.map((item) => {
          if (item.id === id) {
            newLine = { ...item, desc, name };
            return { ...item, desc, name };
          }
          return item;
        });
        return res.json(newLine);
      })();
      return;
    default:
      break;
  }

  const result = {
    list: lineListDataSource,
    pagination: {
      total: lineListDataSource.length,
    },
  };

  res.json(result);
}

export default {
  'GET /api/line': getLines,
  'POST /api/line': postLine,
};
